import { format } from "date-fns";

/**
 *日期距离今天还有几天
 */
export function daysUntilExpire(expireDate: string): number {
  // 将字符串日期转换为 Date 对象
  const expire = new Date(expireDate);
  const now = new Date();

  // 计算两个日期之间的毫秒差异
  const diffTime = expire.getTime() - now.getTime();

  // 将毫秒差异转换为天数并取整
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  return diffDays;
}

export enum TimeFormat {
  DATE = "yyyy-MM-dd",
  DATEMINUTE = "yyyy-MM-dd HH:mm",
  DATETIME = "yyyy-MM-dd HH:mm:ss",
  COMPACTTIME = "yyyyMMddHHmmss",
  COMPACTDATE = "yyyyMMdd",
}

export function timeFormat(
  date?: string | number | Date,
  fmt = TimeFormat.DATETIME
) {
  return date && format(date, fmt);
}

/**
 * 根据规则显示日期：刚刚、几分钟前、几小时前、几天前
 */
export function fromNow(inputTime: string) {
  const now = new Date();
  const diff = (now.getTime() - new Date(inputTime).getTime()) / 1000; // 时间差以秒为单位
  const minute = 60;
  const hour = 60 * minute;
  const day = 24 * hour;

  if (diff < minute) {
    return "刚刚";
  } else if (diff < hour) {
    const minutes = Math.floor(diff / minute);
    return `${minutes}分钟前`;
  } else if (diff < day) {
    const hours = Math.floor(diff / hour);
    return `${hours}小时前`;
  } else if (diff < 7 * day) {
    const days = Math.floor(diff / day);
    return `${days}天前`;
  } else {
    return inputTime;
  }
}

// 获取今天的时间范围
export function getTodayRange() {
  const today = new Date();

  // 获取今天的零点
  const startOfDay = new Date(
    today.getFullYear(),
    today.getMonth(),
    today.getDate(),
    0,
    0,
    0
  );

  // 获取今天的23:59:59
  const endOfDay = new Date(
    today.getFullYear(),
    today.getMonth(),
    today.getDate(),
    23,
    59,
    59
  );

  return { startOfDay, endOfDay };
}
